package com.nbk.composition.manager

import com.nbk.composition.error
import java.util.concurrent.ConcurrentHashMap

/**
 * Author:  LuoHaoLun
 * Email :  506503279@qq.com
 * Date  :  2021/6/2
 */
object TeacherAllot {
    private const val MAX_ALLOC = 10
    private val teacherMap = ConcurrentHashMap<Int, Int>()
    fun initTeacherMap(map: Map<Int, Int>) {
        teacherMap.clear()
        teacherMap.putAll(map)
        println(teacherMap)
    }

    fun allot(): Int {
        val entry = teacherMap.minByOrNull { it.value } ?: "还没得老师".error()
        if (entry.value > MAX_ALLOC) "所有老师分配都满了".error()
        teacherMap[entry.key] = entry.value + 1
        return entry.key
    }

    fun add(teacherId: Int) {
        teacherMap[teacherId]?.let { teacherMap.put(teacherId, it + 1) }
    }

    fun remove(teacherId: Int) {
        teacherMap[teacherId]?.let {
            var c = it - 1
            if (c < 0) c = 0
            teacherMap.put(teacherId, c)
        }
    }
}